package com.caine.auth.controller;

import com.caine.auth.config.RsaKeyProperties;
import com.caine.auth.vo.UserVO;
import com.caine.common.entity.R;
import com.caine.common.entity.UserInfo;
import com.caine.common.tool.JWTTool;
import com.caine.common.tool.StringTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: CaineZhu
 * @Description:
 * @Date: Created in 10:54 2021/1/7
 * @Modified By:
 */
@RestController
@RequestMapping("access")
public class TokenController {
    @Autowired
    RsaKeyProperties rsaKeyProperties;

    @Value("${jwt.token.expire}")
    private int expireDate;

    @PostMapping("token")
    public R accessToken(@RequestBody UserVO vo) {
        if (StringTool.isNotEmptyOrNull(vo.getUserName(), vo.getPassword())) {
            if (vo.getUserName().equals("admin") && vo.getPassword().equals("admin")) {
                UserInfo userInfo = new UserInfo();
                userInfo.setUserName("admin")
                        .setPassword("admin")
                        .setAuthorities(Arrays.asList(new String[]{"SELECT", "UPDATE"}));
                String token = JWTTool.generateTokenExpireInSeconds(userInfo, rsaKeyProperties.getPrivateKey(), expireDate);
                Map<String, Object> retMap = new HashMap<>();
                retMap.put("token", token);
                retMap.put("expire", expireDate);
                return R.success(retMap);
            }
        }
        return R.error("登录失败");

    }

}
